package com.NyCloud.controller;


import cn.dev33.satoken.util.SaResult;
import com.NyCloud.entity.Farmer;
import com.NyCloud.entity.Location;
import com.NyCloud.entity.Product;
import com.NyCloud.entity.vo.FarmerVo;
import com.NyCloud.service.IFarmerService;
import com.NyCloud.service.ILocationService;
import com.NyCloud.service.IProductService;
import com.NyCloud.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者
 * @since 2024-07-26
 */
@RestController
@RequestMapping("/farmer")
@Api(tags = "农场信息")
@CrossOrigin
public class FarmerController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IFarmerService farmerService;

    @Autowired
    private IProductService productService;

    @Autowired
    private ILocationService locationService;

    @GetMapping("/list")
    @ApiOperation("全部农场信息")
    public SaResult getCompanyList() {
        List<Farmer> farmers = farmerService.list();
        ArrayList<FarmerVo> farmerVos = new ArrayList<>();
        for (Farmer farmer : farmers) {
            FarmerVo farmerVo = new FarmerVo();
            BeanUtils.copyProperties(farmer, farmerVo);
            List<Product> productList = productService.list(new QueryWrapper<Product>()
                    .eq("user_id", farmer.getUserId()));
            StringBuilder productionInfo = new StringBuilder();
            for (Product product : productList) {

                productionInfo.append(String.format("产品：%s,月需求 %.2f吨,年需求 %.2f吨;",
                        product.getProductName(),
                        product.getMonthlyProduction(),
                        product.getYearlyProduction()));
            }
            Location location = locationService.getOne(new QueryWrapper<Location>()
                    .eq("user_id", farmer.getUserId()));
            farmerVo.setLocation(location);
            farmerVo.setProductionInfo(productionInfo.toString());
            farmerVos.add(farmerVo);
        }
        return SaResult.data(farmerVos);
    }



    @GetMapping("/{userId}")
    @ApiOperation("获取农场信息")
    public SaResult getCompany(@PathVariable Integer userId) {
        Farmer farmer = farmerService.getOne(new QueryWrapper<Farmer>()
                .eq("user_id", userId));
        return SaResult.data(farmer);
    }

    @PostMapping
    @ApiOperation("更新农场信息")
    public SaResult updateCompany(@RequestBody Farmer farmer) {
        farmerService.updateById(farmer);
        return SaResult.ok();
    }
}
